package main

import (
	"flag"
	"github.com/golang/glog"
	"cloud_worm/worm/config"
	"cloud_worm/worm/client/diagnose"
	"math/rand"
	"time"
	"fmt"
	"cloud_worm/worm/client/docker"
	"cloud_worm/worm/client"
	"strings"
	"os"
	"cloud_worm/worm/httpsrv"
)

const (
	// 默认配置地址*****************
	configFile = "./conf/config.conf"

	version = 100100101
)

func main()  {
	//设置log的参数
	flag.Parse()
	glog.MaxSize = 1024 * 1024 * 20

	glog.Infof("Begin worm agent, version: %d", version)

	// 读取配置信息
	err := config.LoadConfig(configFile, version)
	if err != nil {
		glog.Fatal(err.Error())
		return
	}

	if config.CfgInst.StartMode == config.ClientStartMode {
		if err := startClient(); err != nil {
			glog.Fatal(err)
			return
		}
	} else if config.CfgInst.StartMode == config.HttpSrvStartMode {
		if err := startHttpSrv(); err != nil {
			glog.Fatal(err)
			return
		}
	} else {
		glog.Fatalf("start mode error: %s", config.CfgInst.StartMode)
		return
	}

	select {}
	glog.Flush()
	return
}

func startClient() error {
	clientConfig := config.CfgInst.StartConfig.(*config.ClientConfig)

	// 诊断server，Goroutine
	diagnose.Diagnose()

	// 随机等待几秒钟
	randomSleep()
	glog.Infof("url: %s, HttpIntervalTime: %s", clientConfig.ServerSet.RouterURL, clientConfig.ServerSet.RouterInterval)

	// docker信息
	if docker.ContainInfoInst.SystemType == docker.DockerHost {
		docker.ContainInfoInst.LoadIdIPMap()
		go docker.ContainInfoInst.LoadLoop()
	}
	glog.Infof("system type: %d, ip map: %s", docker.ContainInfoInst.SystemType, docker.ContainInfoInst.IPMap)

	// 启动agent
	if err := client.AgentInst.InitAgent(version); err != nil {
		return err
	}
	client.AgentInst.Start(config.CfgInst.LocalAddr)

	// 删除之前的运行目录
	var v int
	if strings.Contains(config.CfgInst.RunMode, "dev") {
		v = 100100101
	} else {
		v = 200100101
	}
	for ; v < version; v++ {
		os.RemoveAll(fmt.Sprintf("/usr/local/cloud_worm/worm/%d", v))
	}

	return nil
}

func startHttpSrv() error {
	return httpsrv.HttpServer()
}

func randomSleep()  {
	var waitSec int
	for i := 0; i < 3; i++ {
		s := rand.NewSource(time.Now().UnixNano())
		r := rand.New(s)
		waitSec = r.Intn(10)
		if waitSec != 0 {
			break
		}
	}
	glog.Info(fmt.Sprintf("waiting %ds .....", waitSec))
	time.Sleep( time.Duration(waitSec) * time.Second)
	return
}
